function isEmptyObject(obj){
     for(let _ in obj){
          return false
     }
     return true
}

// hook setData after onLoad
function sop(o) {
    let cacheData = {}
    o.setCache = function(data) {
        cacheData = Object.assign(cacheData, data)
    }
    const v = Object.assign(o, {
        setData: o.setCache,
    })
    o.request = function({url, delay, success}) {
        // TODO: abort after remove page
        setTimeout(() => {
            success.apply(v, [url+' data'])
            o.updateData()
        }, delay);
    }

    const { onLoad } = o
    o.onLoad = (function(...args) {
        // console.log('onLoad hooks')
        onLoad ? onLoad.apply(o, args) : null
        // afterLoadPage

        const { setData } = o
        o.setData = o.setCache
        o.updateData = function() {
            if (!isEmptyObject(cacheData)) {
                setData(cacheData)
            }
            cacheData = {}
        }

        for (let k in o) {
            // console.log('check', k)
            if (k !== 'onLoad'
                && k !== 'setCache'
                && k !== 'setData'
                && k !== 'updateData'
                && typeof o[k] === 'function') {
                // console.log(k, 'hooks')
                let fn = o[k]
                o[k] = function(...args) {
                    fn.apply(o, args)
                    console.log('cache', cacheData)
                    o.updateData()
                }
            }
        }
    }).bind(o)

    return o
}

function useState(s) {
    let x = s
    function get() {
        return x
    }
    function set(s) {
        x = s
    }
    return [get, set]
}

module.exports = {
    sop,
    useState,
}
